package com.sntk.organauthomanager.infrastructure.service;

import com.sntk.organauthomanager.infrastructure.exception.DataNoLegalException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: ServiceConfig
 * @author: wgchao
 * @createTime: 2020/9/7 4:20 PM
 * @Description: 内部服务注册配置信息
 */
public class ServiceConfig {
    private static Map<String, ServiceConfigInfo> serviceInfoMap = new HashMap<>();
    //同一个IP允许多个服务进行注册
    private static final Boolean SERVICESEXIST = true;

    public static void addService(ServiceConfigInfo serviceInfo){
        if(existService(serviceInfo.getServiceCode()) != null){
            throw new DataNoLegalException("服务注册编号已存在");
        }
        if(!SERVICESEXIST){
            if(existIPService(serviceInfo.getRegisteredIp()) != null){
                throw new DataNoLegalException("该IP地址已经注册过服务");
            }
        }
        serviceInfoMap.put(serviceInfo.getServiceCode(), serviceInfo);
    }

    public static ServiceConfigInfo existService(String code){
        for(Map.Entry<String, ServiceConfigInfo> entry : serviceInfoMap.entrySet()){
            if(entry.getKey().equals(code)){
                return entry.getValue();
            }
        }
        return null;
    }

    public static ServiceConfigInfo existIPService(String ip){
        for(Map.Entry<String, ServiceConfigInfo> entry : serviceInfoMap.entrySet()){
            if(entry.getValue().getRegisteredIp().equals(ip)){
                return entry.getValue();
            }
        }
        return null;
    }

    public static void removeService(String code){
        serviceInfoMap.remove(code);
    }

    public static List<ServiceConfigInfo> findAllService(){
        List<ServiceConfigInfo> serviceInfos = new ArrayList<>();
        for(Map.Entry<String, ServiceConfigInfo> entry : serviceInfoMap.entrySet()){
            serviceInfos.add(entry.getValue());
        }
        return serviceInfos;
    }

    public static void updateService(ServiceConfigInfo serviceInfo){
        serviceInfoMap.put(serviceInfo.getServiceCode(), serviceInfo);
    }
}
